<?php
namespace AuctionCore\AuctionOrder;
use AuctionCore\System\AuctionException;
//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//


/**
* 场次
* @author       爱民
*/
class Scene {
    
    /**
    * 新建场次
    * @param    int $sence_info    场信息[emp_id:操作员工id,starttime:开始时间，endtime:结束时间,name:标题] ,
    *
    * @return   int 返回场次id号
    */
    public static function create($scene_info) {
        foreach (array('name','starttime') as $value) {
            if(!$scene_info[$value])
               AuctionException::make_throw('700001'); 
        }

        $scene_info['createtime'] = date("Y-m-d H:i:s",time());;
        $scene = M('order_scene');
        $insertId = $scene->add($scene_info);
        return $insertId;
    }

    /*
     * 获取有效场次
     * */
    public function get_scenes($map1){
        $map = array();
        $map['status'] = array('eq','1');
        $map['starttime'] = array('gt',date('Y-m-d H:i:s'));
        if(is_array($map1) && !empty($map1)){
            $map = array_merge($map,$map1);
        }
        return M('order_scene')->where($map)->order("scene_id desc")->select();
    }

    /**
     * @param $params
     * @return mixed
     */
    public function getSingleSceneByParams($params)
    {
        $map = [];
        if(!empty($params['starttime'])){
            $map['starttime'] = $params['starttime'];
        }
        if (!empty($params['name'])){
            $map['name'] = $params['name'];
        }
        return M("order_scene")->where($map)->find();
    }

    /*
     * 获取场次信息
     * */
    public function detail($scene_id){
        if(!intval($scene_id)){
            return false;
        }
        return M('order_scene')->find($scene_id);
    }
    /**
    * 更新场次信息
    * @param    int $sence_info    场信息[开始时间，结束时间,标题,描述] ,
    *                             返回成功与否
    * @return   boolean
    */
    public static function change($scene_id,$scene_info) {
            //只能编辑场次状态为1的（即未开始拍卖的）
            $scene = self::detail($scene_id);
            if(!$scene){
                AuctionException::make_throw('700028');
            }
            if($scene['status']=='2'){
                AuctionException::make_throw('700029');
            }
            if($scene['status']=='3'){
                AuctionException::make_throw('700030');
            }

            $ok = M('order_scene')->where("scene_id='".$scene_id."'")->save($scene_info);
            return $ok;
    }

    /**
     * 得新计算场次内非定时单的开拍时间
     * @param $scene_id
     * @return bool
     */
    public function re_compute_starttime($scene_id){
            $res = M('order_scene')->alias('os')->field('os.starttime,o.order_id,o.act_elapsed_time,o.est_elapsed_time')->join(C('DB_PREFIX')."order o ON o.scene_id=os.scene_id")
                ->where("os.scene_id='".$scene_id."' AND o.is_timing_order=0 AND o.rank>0 AND o.status NOT IN(2,6,12)")->order("o.rank")
                ->select();
            $arr = array();
            $timestamp = 0;
            foreach($res as $v){
            $timestamp += $v['act_elapsed_time']>$v['est_elapsed_time']?$v['act_elapsed_time']:$v['est_elapsed_time'];
                $arr[] = $timestamp;
            }
            //
            $rs = array();
            foreach($res as $key=>$val){
                $data = array();
                $data['bidding_start_time'] = date("Y-m-d H:i:0",strtotime($val['starttime'])+$arr[$key-1]);
	            $data['last_time'] = date('Y-m-d H:i:s',time());
                $rs[]=M('order')->where("order_id='".$val['order_id']."'")->save($data);
            }
            return !in_array(false,$rs) ?true:false;
    }

    public function check_starttime($scene_id,$starttime){
            $res = M('order')->where("scene_id='".$scene_id."' and is_timing_order=1 and rank>0 and status not in(2,6,12)")->order('bidding_start_time')->find();
            if($res){
                if(strtotime($res['bidding_start_time'])<strtotime($starttime)){
                   return false;
                }
            }
            return true;
    }
    public static function remove($scene_id){
        $ok = M('order_scene')->where('scene_id=\''.$scene_id.'\'')->delete();
        return $ok;
    }

    /**
     * 获取最近一场的场次信息
     * @return mixed
     */
    public function get_last_scene(){
        $map = array();
        //今明两天的
        $map['starttime'] = array(array('gt', date('Y-m-d 00:00:00')), array('lt', date('Y-m-d 23:59:59', strtotime('+1 day'))));
        $map['status'] = array('in', '1,2');//场次状态 -1禁用 1待拍 2拍卖中 3 完成
        //状态为1,2的
        $res = M('order_scene')->where($map)->order('starttime')->find();
        return $res;
    }

	/**
	 * 根据分公司编号，得到城市编号
	 *
	 * @return mixed
	 */
	public function get_cicy_by_branch_id(){
    	$map = array();
	    $branch_id = $this->user_info['branch_id'] == 0 ? '33':$this->user_info['branch_id'];//如果是总部的话，默认成北京的
	    $map['branch_id'] = array('eq',$branch_id);
	    return M('branch_city')->field('city_code')->where($map)->find();
    }

	/**
	 * 添加或者编辑场次活动
	 *
	 * @param $data 场次活动关系数据
	 * @return bool|mixed
	 */
	public function addOrEditeSceneActivity($data){
    	$scene_id = $data['scene_id'];// 场次编号
	    $map['scene_id'] = ['eq',$scene_id];
	    $obj = M('scene_activity_relation')->where($map)->find();
	    if($obj){
		    $result = M('scene_activity_relation')->where($map)->save($data);
		  //  echo M()->getLastSql();
		    return $result;
	    }else{
		    $result = M('scene_activity_relation')->add($data);
		    //echo M()->getLastSql();
		    return $result;
	    }
    }

	/**
	 * 根据场次编号，删除活动
	 *
	 * @param $data
	 * @return bool
	 */
	public function deleteSceneActivity($data){
	    $scene_id = $data['scene_id'];// 场次编号
	    $map['scene_id'] = ['eq',$scene_id];
	    $result = M('scene_activity_relation')->where($map)->delete();
	    if($result === false){
	    	return false;
	    }else{
	    	return true;
	    }
    }


	/**
	 * 根据场次编号，得到相应的活动信息
	 *
	 * @param $sceneId 场次编号
	 * @return mixed
	 */
	public function getActivityBySceneId($sceneId){
	    $map['relation.scene_id'] = ['eq',$sceneId];
	    $fileds = 'relation.scene_activity_id,activity.branch_id,activity.rules_type,activity.amount';
	    return M('scene_activity_relation')->field($fileds)
		    ->alias('relation')
		    ->join(C('DB_PREFIX').'scene_activity as activity on relation.scene_activity_id = activity.id')
		    ->where($map)
		    ->find();
    }

	/**
	 * 判断活动是否有效
	 *
	 * @param $activityId 活动编号
	 * @param $time 活动时间
	 * @return mixed
	 */
	public function judgeTheActivityWheatherAvailable($activityId, $time){
	    $map['starttime'] = ['elt',$time];
	    $map['endtime'] = ['egt',$time];
	    $map['id'] = ['eq',$activityId];
	    $result = M('scene_activity')->where($map)->find();
	    //echo M()->getLastSql();die();
	    return $result;
    }


	/**
	 *  通过场次，计算拍单金额
	 *
	 * @param $sceneId 场次编号
	 * @param $amount 拍单金额
	 * @return mixed 返回最后金额
	 */
	public function getOrderAmountBySceneId($sceneId, $amount){
		$result = $this->getActivityBySceneId($sceneId);
	    if(empty($result)){ //如果没有活动,则直接返回金额
			return $amount;
	    }else{ //如果有活动
			$sceneActivityId = $result['scene_activity_id'];
		    $rulesType = $result['rules_type'];

		    if($rulesType == 2){ // 如果是规则减免
				$map['scene_activity_id'] = ['eq',$sceneActivityId];
				$map['min_bid_price'] = ['elt',$amount];
				$map['max_bid_price'] = ['egt',$amount];
				$fileds = 'amount';
			    $data = M('activity_rules')->field($fileds)->where($map)->find();
				if($data){
					$lastAmount = $amount - $data['amount'];
					return $lastAmount;
				}
				return $amount;
			}else{ // 如果是统一减免
				$activityAmount = $result['amount'];
				$lastAmount = $amount - $activityAmount;
				return $lastAmount;
			}
	    }
    }

    //查询改场次是否有活动
    public static function is_scene_activity($scene_id){
        $map['sar.scene_id'] = array('eq',$scene_id);
        $map['sa.status'] = array('eq',1); //活动必须为正常状态
        $info = M('scene_activity_relation')->where($map)->alias("sar")->field('sar.id,sar.scene_id,sar.scene_activity_id,sa.name,sa.type,sa.branch_id,sa.rules_type,sa.amount,sa.status')
            ->join(C("DB_PREFIX")."scene_activity as sa ON sa.id = sar.scene_activity_id")
            ->select();
        return $info;
    }
    public static function get_activity_rules_price($scene_activity_id,$success_price){
        $map['scene_activity_id'] = array('eq',$scene_activity_id);
        $map['min_bid_price'] = array('elt',$success_price);
        $map['max_bid_price'] = array('egt',$success_price);
        $info = M('activity_rules')->where($map)->find();
        return $info['amount'];
    }
}
?>